package com.happy.xiao.consumer.rabbitmq;

import com.happy.xiao.common.rabbitmq.BaseConsumerListener;
import com.happy.xiao.common.rabbitmq.db.entity.MessageLog;
import com.happy.xiao.common.rabbitmq.db.service.IMessageLogService;
import com.happy.xiao.common.utils.StringUtil;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.ChannelAwareMessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.UUID;

@Component("simpleListener")
public class SimpleListener extends BaseConsumerListener implements ChannelAwareMessageListener {




    @Autowired
    IMessageLogService iMessageLogService;

    @Override
    public void onMessage(Message message, Channel channel) throws Exception {

        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        String messageId = message.getMessageProperties().getMessageId();
        String redisPrefix = "rabbitmq-";

        try {
            System.out.println("deliveryTag  =====  " + deliveryTag);
            System.out.println("messageId  =====  " + messageId);

            byte[] msg = message.getBody();

            String msgStr = new String(msg, "UTF-8");
            System.out.println(msgStr);

            MessageLog messageLog = new MessageLog(UUID.randomUUID() + "", "test", "test", "test",
                    String.valueOf(1000), StringUtil.time());
            iMessageLogService.add(messageLog);

            handleSuccessMessage(channel, message, redisPrefix);

        } catch (Exception e) {
            e.printStackTrace();

            // TODO: 这里要用缓存控制一下，重入队列
            // 先判断redis中，是否存在着个异常消息次数，如果不存在，则添加到redis
            // 判断redis中的次数，如果超过一定的次数，如10次，则把这个消息丢弃
            handleErrorMessage(channel, message, redisPrefix, 7);
        }
    }
}
